如何在 Rails 5 中使用 RSpec 测试模型中的关联?
How do I test associations in models with RSpec in Rails 5?
我是 Rails 5 的新手,正在尝试测试一个极其简单的数据库模型,但我似乎做不好。我正在尝试测试 has_many
关联。
模型代码如下所示:
app/models/database_models/response.rb
module DatabaseModels
class Response < ApplicationRecord
has_many :question_responses, :class_name => 'DatabaseModels::
QuestionResponse'
end
end
规范 (RSpec) 看起来像这样
spec/models/screener_response_spec.rb
require 'rails_helper'
describe DatabaseModels::Response, type: :model do
it { is_expected.to have_many(:question_responses) }
end
它失败了:
expected #<DatabaseModels::Response:0x007fd91ccda210> to respond to `has_many?`
我做错了什么?
测试这个的一种方法是测试实际行为:
require 'rails_helper'
describe DatabaseModels::Response, type: :model do
let(:response) { described_class.new }
it 'has many question responses' do
expect( response.question_responses.new ).to be_a_new DatabaseModels::
QuestionResponse
end
end
否则你可以使用反射,这基本上就是 shoulda
所做的:
require 'rails_helper'
describe DatabaseModels::Response, type: :model do
it 'has many question responses' do
relation = described_class.reflect_on_association(:question_responses)
expect(relation.macro).to eq :has_many
end
end
我是 Rails 5 的新手,正在尝试测试一个极其简单的数据库模型,但我似乎做不好。我正在尝试测试 has_many
关联。
模型代码如下所示:
app/models/database_models/response.rb
module DatabaseModels
class Response < ApplicationRecord
has_many :question_responses, :class_name => 'DatabaseModels::
QuestionResponse'
end
end
规范 (RSpec) 看起来像这样
spec/models/screener_response_spec.rb
require 'rails_helper'
describe DatabaseModels::Response, type: :model do
it { is_expected.to have_many(:question_responses) }
end
它失败了:
expected #<DatabaseModels::Response:0x007fd91ccda210> to respond to `has_many?`
我做错了什么?
测试这个的一种方法是测试实际行为:
require 'rails_helper'
describe DatabaseModels::Response, type: :model do
let(:response) { described_class.new }
it 'has many question responses' do
expect( response.question_responses.new ).to be_a_new DatabaseModels::
QuestionResponse
end
end
否则你可以使用反射,这基本上就是 shoulda
所做的:
require 'rails_helper'
describe DatabaseModels::Response, type: :model do
it 'has many question responses' do
relation = described_class.reflect_on_association(:question_responses)
expect(relation.macro).to eq :has_many
end
end