我正在使用Rspec测试Ruby类。我想在这两个上下文之间更改实例double的返回值,即,我想要tallied_data.a_conv,tallied_data.a_nonconv等,以返回“当A是赢家”上下文时的不同值。有没有办法,我可以做到这一点,而不必创建一个新的instance_double并重复第3-9行中的所有代码?有没有不同的方法来解决这个问题?
describe ABSplitTest do
describe "#test_winner" do
let(:tallied_data) do
instance_double("ABDataSummary",
a_conv: 50, a_nonconv: 51,
b_conv: 52, b_nonconv: 53,
to_h: { a: { conv: 50, nonconv: 51 }, b: { conv:52, nonconv: 53 } }
)
end
subject(:sample_test) { ABSplitTest.new(tallied_data) }
context "when there is no winner" do
it "returns that there is no clear winner" do
expect(sample_test.test_winner).to \
eq("No winner at 0.05 significance")
end
end
context "when A is winner" do
it "returns that A is winner" do
expect(sample_test.test_winner).to \
eq("No winner at 0.05 significance")
end
end
答案 0 :(得分:0)
您在测试中所做的事情及其与tallied_data
的关系并不十分清楚,但您可以通过let
在上下文中设置具体值。 let
值在第一次使用之前无法解析,因此如果需要,您可以根据内部上下文中的值进行组合。
例如:
describe ABSplitTest do
describe "#test_winner" do
let(:tallied_data) do
instance_double("ABDataSummary",
a_conv: a_conv, a_nonconv: 51,
b_conv: 52, b_nonconv: 53,
to_h: { a: { conv: 50, nonconv: 51 }, b: { conv:52, nonconv: 53 } }
)
end
subject(:sample_test) { ABSplitTest.new(tallied_data) }
context "when there is no winner" do
let(:a_conv) { 50 }
it "returns that there is no clear winner" do
expect(sample_test.test_winner).to \
eq("No winner at 0.05 significance")
end
end
context "when A is winner" do
let(:a_conv) { 70 }
it "returns that A is winner" do
expect(sample_test.test_winner).to \
eq("No winner at 0.05 significance")
end
end