使用rspec和factory测试创建操作失败

时间:2013-11-16 19:03:29

标签: ruby-on-rails ruby rspec factory-bot

我正在尝试在我的rails 4 app中测试post / create控制器操作,但它失败了。

这是脚手架生成的测试:

it "assigns a newly created project as @project" do
  post :create, {:project => valid_attributes}, valid_session
  assigns(:project).should be_a(Project)
  assigns(:project).should 
end

以下是我重构后与FactoryGirl一起使用的代码

  it "assigns a newly created project as @project" do
    project = FactoryGirl.create(:post)
    assigns(project).should be_a(Project)
    assigns(project).should be_persisted
  end

所以它失败了:

 Failure/Error: assigns(project).should be_a(Project)
   expected nil to be a kind of Project(id: integer, title: string, description: text, created_at: datetime, updated_at: datetime)

我不知道为什么project在分配方法中返回nil。我已经检查过它以确保它正在返回一个合适的项目。

是的,这是我的项目工厂:

factory :project do
  title "MyString"
  description "MyText"
  users {[FactoryGirl.create(:user)]}
end 

提前致谢!

1 个答案:

答案 0 :(得分:1)

assigns(project)方法调用返回Rails中@project实例变量的值。调用FactoryGirl方法对此变量没有影响,因此它的计算结果为nil