RSpec 和 FactoryGirl 对表演动作的解释
RSpec and FactoryGirl explanation for show action
刚开始和 RSpec 和 Factory Girl 一起学习测试,遇到了这个测试
describe "#show" do
it "render the show template" do
get :show, id: FactoryGirl.create(:opinion)
expect(response).to render_template :show
end
end
要呈现展示页面,我知道它需要 ID。我只是想明白这行是什么意思id: FactoryGirl.create(:opinion)
。
现在我认为这意味着 "get the ID of the Opinion object that FactoryGirl is creating",但我想确定一下。
此外,我只是想知道是否有其他方法可以使用另一种语法编写相同的测试?
get :show, id: FactoryGirl.create(:opinion)
在这里,您发出了一个 GET
请求,并将 :id
参数与其一起传递,以告诉它显示特定 opinion
的页面。
id: FactoryGirl.create(:opinion)
这是发出 /show
请求所必需的 param
,因此您在发出请求时会传递它。否则测试将失败。在这里,您要传递 opinion
对象,Rails 将为您检索 id
。或者,您可以发送 id
本身而不是 opinion
对象。所以,这也行得通:
get :show, id: FactoryGirl.create(:opinion).id
更简洁的方式:
您先定义 opinion
对象:
let(:test_opinion) { FactoryGirl.create(:opinion) }
然后,您将在稍后的测试中使用 test_opinion
对象或其 id
:
describe 'GET #show' do
context "existing opinion" do
it 'responds with success' do
get :show, id: test_opinion.id
expect(response.status).to eq(200)
expect(response).to render_template :show
end
end
end
您还可以根据请求传递更多 params
以正确呈现模板。
例如如果需要,您可以发送更多逗号分隔 params
:
get :show, format: :json, id: FactoryGirl.create(:opinion)
刚开始和 RSpec 和 Factory Girl 一起学习测试,遇到了这个测试
describe "#show" do
it "render the show template" do
get :show, id: FactoryGirl.create(:opinion)
expect(response).to render_template :show
end
end
要呈现展示页面,我知道它需要 ID。我只是想明白这行是什么意思id: FactoryGirl.create(:opinion)
。
现在我认为这意味着 "get the ID of the Opinion object that FactoryGirl is creating",但我想确定一下。
此外,我只是想知道是否有其他方法可以使用另一种语法编写相同的测试?
get :show, id: FactoryGirl.create(:opinion)
在这里,您发出了一个 GET
请求,并将 :id
参数与其一起传递,以告诉它显示特定 opinion
的页面。
id: FactoryGirl.create(:opinion)
这是发出 /show
请求所必需的 param
,因此您在发出请求时会传递它。否则测试将失败。在这里,您要传递 opinion
对象,Rails 将为您检索 id
。或者,您可以发送 id
本身而不是 opinion
对象。所以,这也行得通:
get :show, id: FactoryGirl.create(:opinion).id
更简洁的方式:
您先定义 opinion
对象:
let(:test_opinion) { FactoryGirl.create(:opinion) }
然后,您将在稍后的测试中使用 test_opinion
对象或其 id
:
describe 'GET #show' do
context "existing opinion" do
it 'responds with success' do
get :show, id: test_opinion.id
expect(response.status).to eq(200)
expect(response).to render_template :show
end
end
end
您还可以根据请求传递更多 params
以正确呈现模板。
例如如果需要,您可以发送更多逗号分隔 params
:
get :show, format: :json, id: FactoryGirl.create(:opinion)