我是Rspec的新手。我写了一个rspec来检查名为“Lead controller”的控制器的创建动作。现在我想编写一个规范,检查名为“status”的属性设置为“LEAD”。我想在创建潜在客户后从应用程序的帖子数据中检查它。如何使用'expect'块和'post:create'来检查状态?
describe 'POST #create' do
it "should create a lead" do
my_lead = Fabricate(:project, id: Faker::Number.number(10))
expect{
post :create, project: my_lead.attributes
}.to change(Project, :count).by(1)
end
it "should assign the status to lead" do
my_lead = Fabricate(:project, id: Faker::Number.number(10))
my_lead.status.should == "LEAD"
end
end
答案 0 :(得分:1)
您的第二个测试必须测试创建对象的状态是否按预期设置:
describe '#create' do
let!(:my_lead) { Fabricate(:project, id: Faker::Number.number(10)) }
it "should create a lead" do
expect{ post :create, project: my_lead.attributes }
.to change(Project, :count).by(+1)
end
it "should assign the status to lead" do
post :create, project: my_lead.attributes
expect(Project.last.status).to eq('LEAD')
end
end
答案 1 :(得分:0)
您可以使用assigns(:instance_variable_name)
方法访问控制器中已分配的实例变量。
例如,假设您的create
操作如下所示:
def创建 @lead = Project.create(project_params) 端
然后,您可以通过调用@lead
访问RSpec控制器示例中的assigns(:lead)
。请注意,符号文本与实例变量名称完全匹配。
因此,您更新的测试看起来像这样:
it "should assign the status to lead" do
my_lead = Fabricate(:project, id: Faker::Number.number(10))
post :create, project: my_lead.attributes
# Test that the status for @lead in our controller matches what we expect it to:
assigns(:lead).status.should == "LEAD"
end
答案 2 :(得分:0)
最后,我想出了一个小问题,解决了我的问题
describe 'POST #create' do
it "should create a lead" do
my_lead = Fabricate(:project, id: Faker::Number.number(10))
expect{
post :create, project: my_lead.attributes
}.to change(Project, :count).by(1)
end
it "should assign the status to lead" do
my_lead = Fabricate(:project, id: Faker::Number.number(10))
post :create, project: my_lead.attributes
expect(Project.last.status).to eq('LEAD')
end
end